<template>
  <div>
    <list-page ref="listPage" :stripe='true' :columns='tableColumns' :columnKey='columnKey' :data='listData' :loading='loading' :totalCount='totalCount' :pageIndex='pageIndex' @load-data='loadData' @show-add='showAddModel' @show-edit='showEditModel' @delete-handle='deleteActionHandle'>
    </list-page>

    <Modal :title="modalTitle" v-model="modalShow" :mask-closable="false" :closable="false" :footer-hide="true" scrollable class-name="vertical-center-modal">
      <Form :ref="formRef" :model="formData" label-position="right" :rules="formValidateRule" :label-width="100">
        <input v-model="formData.userId" name="userId" type="hidden">
        <FormItem label="登录账号" prop="account">
          <Input v-model="formData.account" name="account" placeholder="登录账号"></Input>
        </FormItem>
        <FormItem label="登录密码" prop="userPass">
          <Input v-model="formData.userPass" name="userPass" placeholder="登录密码"></Input>
        </FormItem>
        <FormItem label="用户姓名" prop="userName">
          <Input v-model="formData.userName" name="userName" placeholder="用户姓名"></Input>
        </FormItem>
        <FormItem label="性别">
          <RadioGroup v-model="formData.sex">
            <Radio label="1">男</Radio>
            <Radio label="0">女</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="邮箱" prop="email">
          <Input v-model="formData.email" name="email" placeholder="邮箱"></Input>
        </FormItem>
        <FormItem label="用户类型">
          <RadioGroup v-model="formData.userType">
            <Radio label="1">普通用户</Radio>
            <Radio label="0">管理员</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="用户角色">
          <CheckboxGroup v-model="formData.roleIds">
            <Checkbox v-for='(item) in roles' v-bind:key="item.roleId" :label="item.roleId"> {{ item.roleName}}</Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem>
          <div style="float: right;">
            <Button style="margin-right: 10px" @click="formCancelHandle">取消</Button>
            <Button type="primary" @click="formSaveHandle">保存</Button>
          </div>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import ListPage from '@/components/list-page'
import { mapActions } from 'vuex'
export default {
  name: 'UserManage',
  components: {
    ListPage
  },
  data () {
    return {
      tableColumns: [
        {
          type: 'index',
          title: '序号',
          align: 'center',
          width: 60
        },
        {
          title: '帐户',
          key: 'account'
        },
        {
          title: '姓名',
          key: 'userName'
        },
        {
          title: '用户类型',
          key: 'userType',
          render: (h, params) => {
            let userTypeName = '管理员'
            if (params.row.userType === '1') {
              userTypeName = '普通用户'
            }
            return h('div', [
              h(
                'span',
                {
                  style: {
                    marginRight: '5px',
                    marginLeft: '5px'
                  }
                },
                userTypeName
              )
            ])
          }
        },
        {
          title: '状态',
          key: 'userLock',
          render: (h, params) => {
            let userLockName = '正常'
            if (params.row.userLock === '1') {
              userLockName = '锁定'
            }
            return h('div', [
              h(
                'span',
                {
                  style: {
                    marginRight: '5px',
                    marginLeft: '5px'
                  }
                },
                userLockName
              )
            ])
          }
        }
      ],
      columnKey: 'userId',
      listData: [],
      roles: [],
      rolesLoaded: false,
      loading: false,
      totalCount: 100,
      pageIndex: 1,
      modalTitle: 'title',
      modalShow: false,
      formRef: 'editForm',
      formData: {},
      formValidateRule: {}
    }
  },
  methods: {
    ...mapActions('userStore', [
      'getValidateRule',
      'loadList',
      'getData',
      'save',
      'delete'
    ]),
    ...mapActions('userRoleStore', ['loadUserRoleAll']),
    loadRoles: function () {
      if (!this.rolesLoaded) {
        this.loadUserRoleAll()
          .then(response => {
            this.$Message.info('用户角色列表加载成功')
            this.roles = response.data
            this.rolesLoaded = true
          })
          .catch(() => {
            this.$Message.error('用户角色列表加载失败')
          })
      }
    },
    loadData: function (pageInfo) {
      // console.log('>> load-data')
      if (!pageInfo) {
        pageInfo = {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize
        }
      } else {
        this.pageIndex = pageInfo.pageIndex
      }
      // console.log(pageInfo)
      this.loading = true
      this.loadList(pageInfo)
        .then(res => {
          this.totalCount = res.data.total
          this.listData = res.data.list.map((item, index) => {
            let itemMap = this.$contextUtils.convertObjectNumberPropertieToString(
              item
            )
            return itemMap
          })
          this.loading = false
        })
        .catch(err => {
          console.log(err)
          this.loading = false
        })
    },
    clearFormData: function () {
      this.$refs[this.formRef].resetFields()
      this.formData = {}
    },
    showAddModel () {
      this.clearFormData()
      this.loadRoles()
      this.formData = {
        sex: '1',
        email: 'wyy@qq.com',
        userType: '1'
      }
      console.log('showAdd')
      this.modalTitle = '新增'
      this.modalShow = true
    },
    showEditModel (params) {
      this.clearFormData()
      this.loadRoles()
      this.modalTitle = '编辑'

      this.getData({ userId: params.row.userId })
        .then(response => {
          // this.$Message.info('用户信息加载成功')
          this.formData = this.$contextUtils.convertObjectNumberPropertieToString(
            response.data
          )
          this.modalShow = true
          // console.log(this.formData)
        })
        .catch(() => {
          this.$Message.error('用户信息加载失败')
        })
    },
    deleteActionHandle (params) {
      // console.log(params.row.userId)
      this.delete({
        userId: params.row.userId
      })
        .then(res => {
          // console.log(res)
          this.$Message.info('删除成功')
          this.loadData()
        })
        .catch(err => {
          this.$Message.error(err)
        })
    },
    formCancelHandle () {
      this.modalShow = false
    },
    formSaveHandle () {
      this.$refs[this.formRef].validate(valid => {
        if (!valid) {
          this.$Message.error('输入信息不合法')
        } else {
          // console.log(this.formData)
          this.save(this.formData)
            .then(res => {
              this.clearFormData()
              this.modalShow = false
              this.$Message.info('保存成功')
              this.loadData()
            })
            .catch(err => {
              this.$Message.error('登录帐户已经存在或服务异常')
              console.log('>>>err:', err)
            })
        }
      })
    }
  },
  created () {
    // console.log('>> created....')
    // this.$refs['listPage'].loadData()
    // 加载验证规则
    this.getValidateRule().then(val => {
      this.formValidateRule = {}
      for (let ruleColumn in val) {
        this.formValidateRule[ruleColumn] = val[ruleColumn]
      }
    })
  },
  beforeCreate () {
    // console.log(this.$router)
  }
}
</script>

<style>
</style>
